/*
 * @Description: 注册应用
 * @Author: huacong
 * @Date: 2020-11-02 15:24:57
 * @LastEditTime: 2020-12-02 16:16:52
 * @LastEditors: huacong
 */
import Vue from 'vue'
import axios from 'axios'
import config from '@/config/defaultSetting'
import { getQueryString, listToTree } from '@/utils/util'
import Cookie from 'js-cookie'

import { notification } from 'element-ui'

window.pending = []

const startApp = function (chunk, { router, store, to, next }, cb) {
  // 访问的url，会带一个参数_csrf,拿到这个参数放在请求头或者url后面，再请求后端
  const _csrf = getQueryString('_csrf') || Cookie.get('_csrf') || Cookie.get('XSRF-TOKEN') || ''
  Vue.prototype._csrf = _csrf

  // 获取配置文件——获取接口请求的基础路径
  axios.get(process.env.BASE_URL + 'config.json').then(res => {
    // const BASE_ORIGIN_PARENT = res.data.BASE_ORIGIN_PARENT || window.top.document.location.host
    const BASE_URL = res.data.changeBase ? res.data.BASE_URL : config.baseUrl

    // 基础地址
    Vue.prototype.BASE_URL = BASE_URL + 'web/'
    Vue.prototype.BASE_ORIGIN = res.data.changeBase ? res.data.BASE_ORIGIN : ''

    // 获取路由菜单，统一门户
    axios
      .get(BASE_URL + 'api/getAuthResu', {
        // params: { sysId: 3 },
        timeout: 10000, // 请求超时时间
        withCredentials: true,
        headers: {
          'X-XSRF-TOKEN': _csrf
        }
      })
      .then(res => {
        if (res.status === 200 && res.data.code === 0) {
          const regexp = /([\w+]:)+/
          const list = res.data.data
            .filter(x => !regexp.test(x.resuId))
            .map(x => {
              const keyArr = x.resuId.split('_')
              x.parentName = keyArr.slice(0, keyArr.length - 1).join('_')
              x.name = keyArr[keyArr.length - 1]
              x.path = '/' + chunk + '/' + keyArr.splice(1, keyArr.length).join('/')
              return x
            })
            .filter(p => p.resuId.startsWith(chunk))
          const tree = []
          listToTree(list, tree, '', 'resuId', 'parentName')
          console.log(tree)
          store.commit('SET_PERMISSIONS', list)
          // 组装路由
          store.dispatch('GenerateRoutes', tree).then((addRouters) => {
            router.addRoutes(addRouters)
            const redirect = decodeURIComponent(to.path)
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
          // eslint-disable-next-line
          if (cb) {
            // eslint-disable-next-line
            cb({ list, tree })
          }
        } else {
          notification.error({
            message: res.data ? res.data.data : res.status,
            description: res.data ? res.data.message : '请求异常'
          })
        }
      })
      .catch(err => {
        console.log(err)
        // eslint-disable-next-line
        if (cb) {
          // eslint-disable-next-line
          cb({})
        }
      })
  })
}

export default startApp
